import { Injectable } from '@angular/core';
import { HttpClient } from '../../../providers/httpClient';
import { Config } from '../../../providers/config';
import { Common } from '../../../providers/common';

import { Storage } from '@ionic/storage';
import { FlowParmeter } from './flowParmeter.model';

import _ from 'lodash';

@Injectable()
export class DraftDetailService {
  // 出差申请:ccsq,出勤变更:cqbg,公务外出:gwwc,请休假申请:qxjsq, xgipoxj:新股IPO询价
  type;
  bomids = {
    "cjsq": "T_HR_ChuJingSQ",
    "ccsq": "T_HR_ChuChai",
    "cqbg": "T_HR_ChuQinBG",
    "gwwc": "T_HR_GongWuWC",
    "qxjsq": "T_HR_QingJia",
    "xgipoxj": "T_TZ_Inquiry",
    "xgiposg": "T_TZ_XGWSRG"
  }

  dirids = {
    "cjsq": "CMHRKQCJ",
    "ccsq": "CMHRKQCC",
    "cqbg": "CMHRKQCQ",
    "gwwc": "CMHRKQGW",
    "qxjsq": "CMHRKQQJ",
    "xgipoxj": "OA_INQUIRY",
    "xgiposg": "OA_XGWSRG"
  }

  // "pview": "YES",但是在手机端页面不显示，以下数组保存不显示的fieldid
  hiddenFieldIds = {
    "ccsq": ["ccmx", "depmessage", "chemessage", "manmessage", "attachid", "chuchai_chujing", "appConfirm", "treserved1", "treserved2"], // 出差申请
    "cjsq": ["cdocation", "cjtype", "ccway", "ccreson", "resttel", "cjCation", "restdays", "isFundMgr", "tzxtsqSubFlow", "restreson", "depmessage", "hrmessage", "zhmessage", "fbmessage", "ldmessage", "gdmessage", "attachid"], //出境申请
    "cqbg": ["checktypearray", "BMFZRYJ", "bmzgyj", "checktimearray"], // 出勤变更
    "gwwc": ["bmfzryj", "zhglbyj", "cancelremark"], // 公务外出
    "qxjsq": ["ext-nxjxx", "attach", "rlzyyj", "bmzgyj", "zhbyj", "fgldyj", "zjlyj", "qingjia_chujing", "annual", "isFundMgr"], // 请休假申请
    "xgipoxj" : ["totalrate", "applydate", "bostime", "issuesprice", "attach", "totalitysuggestion", "bankkh", "bankname", "bankamount", "sgamount", "bmfzryj", "fkidea", "dczidea", "tzzjidea", "cbfund", "cbfk", "ljfund", "ljfk", "islj", "isyjlj", "remittance", "hksm", "outinfo", "remitselected", "issueprice", "iszx", "getcbfk", "getljfk", "cborders", "ljorders", "lockperiod", "ispay", "minissueprice", "autocbfk", "autoljfk", "maxissueprice", "push", "remittancemoney", "ljstatus", "wxsgSfzxLR", "randomFlag", "wxzqInfo", "zqPush", "zqZX", "rationCode", "sy_mrgid", "expCBFund", "HKdate", "HKtime", "explanation"], //新股IPO询价
    "xgiposg" : ["isjyzqfh", "bostime", "attach", "dreserved1", "dreserved2", "dreserved3", "BuyInfor", "applydate", "orders", "getfk"]//新股IPO网上申购
  }
  // 在页面不可编辑字段
  disabledFieldIds = {
    "cjsq": ["restdays"], // 出境申请
    "ccsq": ["bosdate"], // 出差申请
    "cqbg": ["bosdate"], // 出勤变更
    "gwwc": ["bosdate"], // 公务外出
    "qxjsq": ['restdays'], // 请休假申请
    "xgipoxj": ["scaleCoefficient", "gearnum"],
    "xgiposg": []
  }

  // 将指定feildid的节点，调整的数组最后
  changePositonFieldIds = {
    "cjsq": ["attachid"], // 出境申请
    "ccsq": ["attachid", "ccreson", "ccway"], // 出差申请
    "cqbg": ["ext-bgmx", "reson", "remark"], // 出勤变更
    "gwwc": [], // 公务外出
    "qxjsq": ["ext-nxjxx", "restreson"], // 请休假申请
    "xgipoxj": ["yjyyj", "tzmsyj", "jjjlyj", "tzjcxzyj", "zyjybidea", "bcyj", "jjkjbidea"] //新股IPO询价
  }

  constructor(
    public httpClient: HttpClient,
    public config: Config,
    public common: Common,
    public storage: Storage,
    public flowParmeter: FlowParmeter
  ) { }

  /**
   * [getDetail 获取businessObjectDesList、workFlowParmeter、flowParmeter]
   * @param {[type]} type [description]
   */
  getDetail(type, taskDetail, ops, bosid) {
    this.type = type;
    var that = this;
    var retVal = {
      "businessObjectDesList": [],
      "workFlowParmeter": {},
      "flowParmeter": {}
    }
    var promise = new Promise(function(resolve, reject) {
      that.getDraftObject(type, ops, bosid).subscribe(data => {
        if (data) {
          console.log("getDetail().data", data);

          if (ops && (ops === "update" || ops === "reject")) {
            retVal.businessObjectDesList = data.businessObject;
            retVal.workFlowParmeter = data.flowParmeter;
          } else {//起草时
            retVal.businessObjectDesList = data.businessObjectDesList;
            retVal.workFlowParmeter = data.workFlowParmeter;
          }

          console.log("taskDetail内容");
          console.log(taskDetail);
          if (taskDetail) {
            _.remove(taskDetail, detail => {
              return detail["dataType"] === "listButton";
            });
            let tempList = _.assignIn(retVal.businessObjectDesList, taskDetail);
            retVal.businessObjectDesList = [];
            _.forEach(tempList, temp => {
              if (temp) {
                retVal.businessObjectDesList.push(temp);
              }
            });
            console.log(retVal.businessObjectDesList);
          }

          retVal.businessObjectDesList = that.setDefSelectOption(retVal.businessObjectDesList); // 初始化下拉框默认值
          retVal.businessObjectDesList = that.setDefDateNode(retVal.businessObjectDesList); // 初始化时间控件默认时间
          retVal.businessObjectDesList = that.setDefVal(retVal.businessObjectDesList); // 设置输入框默认值
          if (ops === "insert") {
            retVal.businessObjectDesList = that.type == "cqbg" ?
              _.concat(retVal.businessObjectDesList, that.createBGMXNode(retVal.businessObjectDesList))
              : retVal.businessObjectDesList; // 添加变更明细节点
          } else {
            retVal.businessObjectDesList = that.type == "cqbg" ?
              _.concat(retVal.businessObjectDesList, that.initBGMXNode(retVal.businessObjectDesList))
              : retVal.businessObjectDesList; // 添加变更明细节点
          }
          retVal.businessObjectDesList = that.type == "qxjsq" ? _.concat(retVal.businessObjectDesList, that.createNXJXXNode()) : retVal.businessObjectDesList; // 添加年休假信息节点
          retVal.businessObjectDesList = that.changeNodePosition(retVal.businessObjectDesList); // 将指定节点移动到节点数组最后
          retVal.businessObjectDesList = that.setProperty(retVal.businessObjectDesList); // 给每个节点添加属性
          if(that.type == "ccsq" || that.type === "cjsq" || that.type == "qxjsq"){
            that.isFundManager().then(function(value){
              retVal.businessObjectDesList = that.setFundMgrPro(retVal.businessObjectDesList,value); // 出差申請流程属性处理,基金经理显示
            });
          }
        }
        resolve(retVal);
      })
    }).then(function() {
      if (retVal.workFlowParmeter) { // workFlowParmeter 不为空
        _.forEach(_.keys(that.flowParmeter), function(key) {
          // 在workFlowParmeter中能匹配到值
          if (retVal.workFlowParmeter[key]) {
            // 初始化flowParmeter值
            retVal.flowParmeter[key] = retVal.workFlowParmeter[key];
          } else {
            retVal.flowParmeter[key] = null;
          }
        })
      }
      return retVal;
    });
    return promise;

  }

  /**
   * [insertDetail 提交起草]
   * @param {[type]} businessObjectDesList [businessObjectDesList]
   * @param {[type]} flowParmeter          [flowParmeter]
   * 返回：{
	 * 		"code" : "1",  // 1 提交成功， 0 提交失败
	 * 		"msg" : "成功！" // 返回信息
	 * }
   */
// <<<<<<< HEAD
  insertDetail(businessObjectDesList, flowParmeter, detailEntry, leaveEntry, ops, bosid) {
	leaveEntry.forEach((v: any) => {
		delete(v.isShow);
	});
	console.log(businessObjectDesList, leaveEntry);
    var that = this;
    var retVal = {
      "code": "1", // 1 成功， 0 失败
      "msg": "成功！"
    }

    if (ops === "update") {
      if (this.type == "ccsq") {
        let appConfirmIndex = _.findIndex(businessObjectDesList, {fieldid: "appConfirm"});
        businessObjectDesList[appConfirmIndex]["fvalue"] = "NO";
      }
    }

    var entrys = this.formateBusinessObjectDes(businessObjectDesList);
    var promise = new Promise(function (resolve, reject) {
      that.insertBusinessObjectDes(entrys, ops, bosid).subscribe(data => {
        console.log("draft.service.insertDetail 插入businessObjectDesList返回结果： ");
        console.log(data);
        if (data.code == "0") {
          if (ops && ops != "insert" && ops != "") {
            data.msg = bosid;
          }
          flowParmeter.bid = data.msg; // 获取bid用于更新
          console.log(flowParmeter.bid);
          retVal.msg = "详细信息插入成功";

          if (that.type === "ccsq" && detailEntry && detailEntry.length > 0) {
              that.insertChuChaiDetail(flowParmeter.bid, detailEntry).subscribe(result => {
                console.log("draft.service.insertChuChaiDetail 插入出差明细结果：");
                console.log(result);

                if (result.code != "0") {
                  retVal.code = "0";
                  retVal.msg += "，出差明细插入失败";
                } else {
                  retVal.msg += "，出差明细插入成功";
                }

                that.updateFlow(flowParmeter, ops).subscribe(data => {
                  console.log("draft.service.insertDetail 更新flowParmeter返回结果： ");
                  console.log(data);

                  if (data.code != "0") {
                    retVal.code = "0";
                    retVal.msg += "，流程信息更新失败！";
                  }

                  resolve(retVal);
                });
              });
          } else {
            if (that.type === "cjsq" && leaveEntry && leaveEntry.length > 0) {
                that.insertCJMXDetail(flowParmeter.bid, leaveEntry).subscribe((result: any) => {
                  console.log("插入出境明细结果：", result, flowParmeter.bid);
                  if (result.code !== "0") {
                    retVal.code = "0";
                    retVal.msg = "，出差明细插入失败";
                  } else {
                    retVal.msg = "，出差明细插入成功";
                  }

                  that.updateFlow(flowParmeter, ops).subscribe(data => {
                    console.log("draft.service.insertDetail 更新flowParmeter返回结果： ");
                    console.log(data);

                    if (data.code != "0") {
                      retVal.code = "0";
                      retVal.msg += "，流程信息更新失败！";
                    }

                    resolve(retVal);
                  });
                });
            } else {
              that.updateFlow(flowParmeter, ops).subscribe(data => {
                console.log("draft.service.insertDetail 更新flowParmeter返回结果： ");
                console.log(data);

                if (data.code != "0") {
                  retVal.code = "0";
                  retVal.msg += "，流程信息更新失败！";
                }

                resolve(retVal);
              });
            }
          }

        } else {
          retVal.code = "0";
          retVal.msg = "详细信息插入失败！";
          resolve(retVal);
        }
      })
    });

    return promise;
    /*=======
     insertDetail(businessObjectDesList, flowParmeter, detailEntry, ops, bosid) {
     var that = this;
     var retVal = {
     "code": "1",  // 1 成功， 0 失败
     "msg": "成功！"
     }

     if (ops === "update") {
     if (this.type == "ccsq") {
     let appConfirmIndex = _.findIndex(businessObjectDesList, {fieldid: "appConfirm"});
     businessObjectDesList[appConfirmIndex]["fvalue"] = "NO";
     }
     }

     var entrys = this.formateBusinessObjectDes(businessObjectDesList);
     var promise = new Promise(function(resolve, reject) {
     that.insertBusinessObjectDes(entrys, ops, bosid).subscribe(data => {
     console.log("draft.service.insertDetail 插入businessObjectDesList返回结果： ");
     console.log(data);
     if (data.code == "0") {
     if (ops === "update") {
     data.msg = bosid;
     }
     flowParmeter.bid = data.msg; // 获取bid用于更新
     console.log(flowParmeter.bid);
     that.updateFlow(flowParmeter, ops).subscribe(data => {
     console.log("draft.service.insertDetail 更新flowParmeter返回结果： ");
     console.log(data);

     if (data.code != "0") {
     retVal.code = "0";
     retVal.msg = "详细信息插入成功，流程信息更新失败！";
     if (that.type === "ccsq") {
     // that.insertChuChaiDetail(flowParmeter.bid, detailEntry)
     if (detailEntry && detailEntry.length > 0) {
     that.insertChuChaiDetail(flowParmeter.bid, detailEntry).subscribe(result => {
     console.log("draft.service.insertChuChaiDetail 插入出差明细结果：");
     console.log(result);
     if (result.code != "0") {
     retVal.code = "0";
     retVal.msg = "详细信息插入成功，流程信息更新失败，出差明细插入失败！";
     } else {
     retVal.code = "0";
     retVal.msg = "详细信息插入成功，流程信息更新失败，出差明细插入成功！";
     }
     resolve(retVal);
     });
     } else {
     resolve(retVal);
     }
     } else {
     resolve(retVal);
     }
     } else {
     if (that.type === "ccsq") {
     // that.insertChuChaiDetail(flowParmeter.bid, detailEntry)
     if (detailEntry && detailEntry.length > 0) {
     that.insertChuChaiDetail(flowParmeter.bid, detailEntry).subscribe(result => {
     console.log("draft.service.insertChuChaiDetail 插入出差明细结果：");
     console.log(result);
     if (result.code != "0") {
     retVal.code = "0";
     retVal.msg = "详细信息插入成功，流程信息更新成功，出差明细插入失败！";
     }
     resolve(retVal);
     });
     } else {
     resolve(retVal);
     }
     } else {
     resolve(retVal);
     }
     }
     });

       } else {
       retVal.code = "0";
       retVal.msg = "详细信息插入失败！";
       resolve(retVal);
       }
       })
       });

       return promise;
       >>>>>>> d0dd4def41a44c87c4c64a6af4c2d5e463dcd939*/
    }

    insertChuChaiDetail(bosid, detailEntry) {
    let that = this;
    let postBody = {
      "module": "OAServer",
      "method": "insertChuChaiDetail",
      "params": {
        bosid: bosid,
        fieldValueList: []
      }
    };

    let fieldValueList = [];
    _.forEach(detailEntry, function(entry) {
      let keys = _.keys(entry.field);
      entry.field["glbosid"] = bosid;
      console.log(keys);
      let entrys = [];
      _.forEach(keys, key => {
        let temp = {
          "key": {
            "attributes": that.common.attributes,
            "$value": ""
          },

          "value": {
            "attributes": that.common.attributes,
            "$value": ""
          }
        };
        temp.key.$value = key;
        temp.value.$value = entry.field[key];
        entrys.push(temp)
      });
      fieldValueList.push({
        "fieldValueMap": {
          "entry": entrys
        }
      })
    });
    postBody.params.fieldValueList = fieldValueList;
    console.log(postBody);

    /*let postBody = {
     "module": "CommonTools",
     "method": "chucaiInsAndDelList",
     "params": {
     "loginId": "system",
     "tableName": "t_hr_chuchai_details",
     "insFields": "numberid,glbosid,bostitle,empid,starttime,endtime,gsname,gscode,remark,address,rescatg,indinf,rescatgname,indinfid,addressid",
     "listData": {
     "fieldValueList":fieldValueList
     },
     "bosid": bosid
     }
     };*/

    console.log(postBody);

    return this.httpClient.post(postBody, {
      isShowLoading: true
    });

    /*return this.httpClient.post(postBody, {
     isShowLoading: true
     });*/
  }

  /**
   * [getFlowParmeter 构建getFlowParmeter对象]
   * @param {[type]} type [description]
   */
  getFlowParmeter(type) {
    var that = this;
    var flowParmeter = {};
    var promise = new Promise(function(resolve, reject) {
      that.getDraftObject(type, null, null).subscribe(data => {
        if (data.workFlowParmeter) { // workFlowParmeter 不为空
          _.forEach(_.keys(that.flowParmeter), function(key) {
            // 在workFlowParmeter中能匹配到值
            if (data.workFlowParmeter[key]) {
              // 初始化flowParmeter值
              flowParmeter[key] = data.workFlowParmeter[key];
            } else {
              flowParmeter[key] = null;
            }
          })
        }
        resolve(flowParmeter);
      })
    })

    return promise;

  }

  /**
   * [getDraftObject 获取页面信息字段businessObjectDesList，流程信息workFlowParmeter,
   * @param {[type]} type [description]
   */
  getDraftObject(type, ops, bid) {
    let postBody = {};

    if (ops && (ops === "update" || ops === "reject")) {
      postBody = {
        "module": "OAServer",
        "method": "getTaskDetail",
        "params": {
          "id": bid
        }
      };
    } else {
      postBody = {
          "module": "OAServer",
          "method": "getDraftDeatail",
          "params": {
            "bomid": this.bomids[type]
          }
      };
    }

    console.log("getDraftObject().postBody", postBody);

    return this.httpClient.post(postBody, {
      isShowLoading: true
    });
  }

  /**
   * [insert 插入起草信息]
   * @param {[type]} params [businessObjectDesList]
   */
  insertBusinessObjectDes(params, ops, bosid) {
    let postBody = {};

    if (ops === "update" || ops === "reject") {
      postBody = {
        "module": "BusinessObject",
        "method": "update",
        "params": {
          "loginId": "fengjk",
          "bosid": bosid,
          "businessobjectDto": {
            "fieldValueMap": {
              "entry": params
            }
          }
        }
      };
    } else {
      postBody = {
        "module": "BusinessObject",
        "method": "insert",
        "params": {
          "loginId": "fengjk",
          "businessobjectDto": {
            "fieldValueMap": {
              "entry": params
            }
          }
        }
      };
    }

    //console.log(postBody);

    return this.httpClient.post(postBody, {
      isShowLoading: true
    });
  }

  updateFlow(params, ops) {
    let handle:any = null;
    switch (ops) {
      case "insert":
        handle = this.updateFlowParmeter(params);
        break;
      case "update":
        handle = this.updateInstance(params);
        break;
      case "reject":
        handle = this.updateInstance(params);
        break;
    }
    return handle;
  }

  /**
   * [updateFlowParmeter 更新流程实例]
   * @param {[type]} params [flowParmeter]
   */
  updateFlowParmeter(params) {
    let postBody = {
      "module": "WorkFlow",
      "method": "workFlowHandle",
      "params": {
        "flowParmeterDto": {
          "flowHandleType": params.flowHandleType,
          "flownumb": params.flownumb,
          "flowStat": params.flowStat,
          "flowdefineid": params.flowdefineid,
          "flowProcessId": params.flowProcessId,
          "flowCurrWkiId": params.flowCurrWkiId,
          "flowNodeInstId": params.flowNodeInstId,
          "flowAppointNodeSel": params.flowAppointNodeSel,  // 驳回的节点
          "flowParentProcessId": params.flowParentProcessId,
          "nextNodeEditor": _.toString(params.nextNodeEditor),
          "flowCurrNode": params.flowCurrNode,
          "nextNodesRadio": params.nextNodesRadio,
          "nextNodeEditorName": _.toString(params.nextNodeEditorName),
          "flowNotion": params.flowNotion,
          "flownotionField": params.flownotionField,
          "flownotionstyle": params.flownotionstyle, //1：覆盖，2：附加
          "flownotioninputstyle": params.flownotioninputstyle,
          "flowIsHuiQian": params.flowIsHuiQian,
          "flowOldNotion": params.flowOldNotion,
          "flowisAllowMultiEditorV": params.flowisAllowMultiEditorV,
          "flowCountermandNotion": params.flowCountermandNotion, // TODO : 驳回意见, 目前都是用flowNotion来接收各类意见，是否需要分开？
          "flowMainSends": params.flowMainSends,
          "flowCopySends": params.flowCopySends,
          "flowSendReads": params.flowSendReads, // 送阅，根据朱文达微信端的逻辑写的
          "flowCmWkiId": params.flowCmWkiId,
          "bomid": params.bomid,
          "isOther": params.isOther,
          "bostitle": params.bostitle,
          "clientType": params.clientType,
          "bid": params.bid,
          "loginId": params.loginId, // 当前登录人的loginid ,TODO需要参数化
          "authLoginId": params.authLoginId // 起草人登录ID, 根据朱文达的逻辑是起草后是不用穿这个参数
        }
      }
    };
    return this.httpClient.post(postBody, {
      isShowLoading: false
    });
  }

  /**
   * [updateInstance 更新流程实例]
   * @param {[type]} params [description]
   */
  updateInstance(params) {
    let postBody = {
      "module": "WorkFlow",
      "method": "workFlowHandle",
      "params": {
        "flowParmeterDto": {
          "flowdefineid": params.flowdefineid,
          "flowProcessId": params.flowProcessId,
          "flowCurrWkiId": params.flowCurrWkiId,
          "flowCmWkiId": params.flowCmWkiId,
          "flownumb": params.flownumb,
          "flowNodeInstId": params.flowNodeInstId,
          "flowHandleType": params.flowHandleType,
          "flowAppointNodeSel": params.flowAppointNodeSel,
          "nextNodeEditor": _.toString(params.nextNodeEditor),
          "nextNodesRadio": params.nextNodesRadio,
          "flowNotion": params.flowNotion,
          "flowCountermandNotion": params.flowCountermandNotion,
          "flowParentProcessId": params.flowParentProcessId,
          "flowStat": params.flowStat,
          "flowCopySends": params.flowCopySends,
          "flowMainSends": params.flowMainSends,
          "flowSendReads": params.flowSendReads,
          "bostitle": params.bostitle,
          "bomid": params.bomid,
          "bid": params.bid,
          "loginId": params.loginId,
          "authLoginId": params.authLoginId,
          "wkPrdid": params.wkPrdid,
          "isOther": params.isOther,
          "variableMap": params.variableMap,
          "indirectNodeMap": params.indirectNodeMap,
          "flownotionField": params.flownotionField,
          "flowOldNotion": params.flowOldNotion,
          "flownotionstyle": params.flownotionstyle,
          "flownotioninputstyle": params.flownotioninputstyle,
          "flowIsHuiQian": params.flowIsHuiQian,
          "flowisAllowMultiEditorV": params.flowisAllowMultiEditorV,
          "nextNodeEditorName": _.toString(params.nextNodeEditorName),
          "flowCurrNode": params.flowCurrNode,
          "clientType": params.clientType,
          "flowOrgTitSel": params.flowOrgTitSel
        }
      }
    };

    console.log("updateInstance().postBody", postBody);

    return this.httpClient.post(postBody, {
      isShowLoading: true
    });
  }


  /**
   * [calculateDays 计算请假天数]
   * @param {[type]} params [{"dateStart","dateEnd":,"resttype":}]
   */
  calculateDays(params) {
    let postBody = {
      "module": "CommonTools",
      "method": "calculateDays",
      "params": {
        "loginId": "",
        "dateStart": params.dateStart,
        "dateEnd": params.dateEnd,
        "resttype": params.resttype
      }
    };

    return this.httpClient.post(postBody, {
      isShowLoading: false

    });
  }

  /**
   * [getAnnualLeave 获取年假信息]
   */
  getAnnualLeave() {
    let postBody = {
      "module": "CommonTools",
      "method": "getHrAnnualLeave",
      "params": {
        "bosid": "0",
        "loginId": "",
      }
    };

    return this.httpClient.post(postBody, {
      isShowLoading: false

    });
  }

  /**
   * 校验申请的年假是否在允许范围内
   * @returns {any}
   */
  ckHrAnnualDay(params) {
    let postBody = {
      "module": "CommonTools",
      "method": "ckHrAnnualDay",
      "params": {
        "bosid": "0",
        "empid": params["empid"],
        "resttype": params["resttype"],
        "startdate": params["startdate"],
        "startpoint": params["startpoint"],
        "enddate": params["enddate"],
        "endpoint": params["endpoint"],
        "restdays": params["restdays"],
      }
    };
    return this.httpClient.post(postBody, {
      isShowLoading: false
    })
  }

  /**
   * [formateBusinessObjectDes 格式化businessObjectDesList，主要用于调用insert接口]
   * @param {[type]} businessObjectDesList [description]
   */
  formateBusinessObjectDes(businessObjectDesList) {
    console.log("draft.service.formateBusinessObjectDes:格式化businessObjectDesList，以便调用接口插入");
    var that = this;
    var entrys = [];
    // 构建节点
    _.forEach(businessObjectDesList, function(data) {
      let temp = {
        "key": {
          "attributes": that.common.attributes,
          "$value": ""
        },

        "value": {
          "attributes": that.common.attributes,
          "$value": ""
        }
      }
      temp.key.$value = data["fieldid"];
      temp.value.$value = data["fvalue"];
      entrys.push(temp);
    })

    // 追加bomid
    let bomid = {
      "key": {
        "attributes": that.common.attributes,
        "$value": "bomid"
      },
      "value": {
        "attributes": that.common.attributes,
        "$value": this.bomids[this.type]
      }
    }
    // 追加dirid
    let dirid = {
      "key": {
        "attributes": that.common.attributes,
        "$value": "dirid"
      },
      "value": {
        "attributes": that.common.attributes,
        "$value": this.dirids[this.type]
      }
    }
    entrys.push(bomid);
    entrys.push(dirid);
    return entrys;
  }

  /**
   * [changeNodePosition 调整字段在数组最后，如：将'出差事由' 调整到数组的最后，即在'查看流程'之后显示]
   * @param {[type]} listData [页面显示字段数组]
   * @param {[type]} item     [字段对象]
   * 出差申请：'附件','出差事由'，'经由线路' 调整到 '查看流程' 之后显示
   *          ('attachid', 'ccway', 'ccreson')
   *
   */
  changeNodePosition(listData) {
    console.log("##draft.detai.changeNodePosition 将指定节点移动到节点数组最后");
    // 该数组元素顺序，将影响页面显示的顺序，index大的排在后
    var fieldids = this.changePositonFieldIds[this.type];
    // 过滤出需要调整的字段
    var nodes = _.filter(listData, _.conforms({
      'fieldid': function(n) {
        if (_.indexOf(fieldids, n) > -1) {
          return true
        } else {
          return false
        }
      }
    }));
    //console.log(nodes);
    // 先移除要调整位置的节点
    listData = _.pullAll(listData, nodes);

    //根据数组指定的顺序追加到数组最后
    _.forEach(fieldids, function(fieldid) {
      let temp_field = _.find(nodes, { "fieldid": fieldid });
      if (temp_field) {
        listData = _.concat(listData, temp_field);
      }
    });

    return listData;
  }

  /**
   * [setProperty 给每个节点添加是否在页面显示属性,是否可编辑属性]
   * @param {[type]} listData [businessObjectDesList]
   */
  setProperty(listData) {
    var that = this;
    console.log("##draft.service.setProperty 给每个节点添加是否在页面显示属性");
    console.log(listData);
    _.forEach(listData, function(data) {
      // 设置页面是否显示属性
      if (_.indexOf(that.hiddenFieldIds[that.type], data["fieldid"]) > -1) {
        data["isShow"] = false;
      } else {
        data["isShow"] = true;
      }
      // 设置是否可编辑属性
      if (_.indexOf(that.disabledFieldIds[that.type], data["fieldid"]) > -1) {
        data["isDisabled"] = true;
      } else {
        data["isDisabled"] = false;
      }
    })
    return listData;
  }

  /**
   * [setDefDateNode 如果时间控件值为空，初始化时间控件默认为当天]
   * @param {[businessObjectDesList]} ndoes [businessObjectDesList]
   */
  setDefDateNode(businessObjectDesList) {
    console.log("##draft.detial.setDefDateNode 初始化时间控件默认为当天");
    var that = this;
    var dataNodes = _.filter(businessObjectDesList, { "dataType": "BT03", "type": "BT01" });

    _.forEach(dataNodes, function(data) {
      if (data["fvalue"] != undefined) {
        data["fvalue"] = data["fvalue"] ? data["fvalue"] : that.common.getNowFormatDate();
      }
    })

    return businessObjectDesList;
  }

  /**
   * [setDefSelectOption 如果下拉控件值为空，初始化下拉控件、单选和复选控件为选项的默认值]
   * 1.type:BT02 下拉框
   * 2. type:BT03 and multiSelect: NO, type:BT03 and multiSelect: YES 单选和复选
   * @param {[type]} businessObjectDesList [businessObjectDesList]
   */
  setDefSelectOption(businessObjectDesList) {
    console.log("##draft.detial.setDefDateNode 如果下拉控件值为空，初始化下拉控件、单选和复选控件为选项的默认值");

    var that = this;
    var bt02Nodes = _.filter(businessObjectDesList, { "type": "BT02" });
    var bt03Nodes = _.filter(businessObjectDesList, { "type": "BT03", "multiSelect": "NO" });
    var dataNodes = _.union(bt02Nodes, bt03Nodes);
    var ipoMarketNode = _.filter(businessObjectDesList, { "fieldid" : "market"});

    _.forEach(dataNodes, function(data) {
      if (data["fvalue"] != undefined) {
        //data["fvalue"] = data["fvalue"] ? data["fvalue"] : data["fieldvalDtos"][0]["fvau"]; // 将第一个作为默认选项

        // 根据默认选项设置
        let nodes = _.filter(data["fieldvalDtos"], { "defu": "YES" });
        data["fvalue"] = data["fvalue"] ? data["fvalue"] : _.toString(_.map(nodes, "fvau"));

        //询价方式未设置默认项，但默认显示“初步询价直接定价”特殊处理
        if(data["fieldid"] === "newStDjtype") {
          let methods = _.filter(data["fieldvalDtos"], { "fdval": "初步询价直接定价" });
          data["fvalue"] = data["fvalue"] ? data["fvalue"] : _.toString(_.map(methods, "fvau"));
        }

      }
    })

    //新股IPO询价，所属市场下拉框只显示上海、深圳
    if (this.type === 'xgipoxj') {
      let ipoMarketOption = ipoMarketNode[0]["fieldvalDtos"];
      ipoMarketNode[0]["fieldvalDtos"] = _.slice(ipoMarketOption, 0 , 2);
    }

    return businessObjectDesList;
  }

  setDefVal(businessObjectDesList) {
    console.log("##draft.detial.setDefVal 设置默认标题、规模系数、中签率");
    if (this.type === 'xgipoxj') {
      _.find(businessObjectDesList, {fieldid: "bostitle"})["fvalue"] = _.replace(this.common.getNowFormatDate(), /-/g, '') + '新股询价';
      _.find(businessObjectDesList, {fieldid: "scaleCoefficient"})["fvalue"] = 0.9; // 预设规模系数
      _.find(businessObjectDesList, {fieldid: "gearnum"})["fvalue"] = 1;
      _.find(businessObjectDesList, {fieldid: "predictrate"})["fvalue"] = 0.5; //预设中签率
    } else if (this.type === 'xgiposg') {
      _.find(businessObjectDesList, {fieldid: "bostitle"})["fvalue"] = _.replace(this.common.getNowFormatDate(), /-/g, '') + '网上申购';
      _.find(businessObjectDesList, {fieldid: "RateForecast"})["fvalue"] = 0.5; //预设中签率
    }
    return businessObjectDesList;
  }

  /**
   * [bgmxChange 变更明细控件，明细有变化时调用该方法修改'变更时段'和'考勤变更时间'节点的fvalue]
   * @param {[node]} item [节点]
   * @param {[businessObjectDesList]} item [description]
   */
  bgmxChange(node, businessObjectDesList) {
    console.log("##draft.service.bgmxChange：变更明细赋值");
    if (node.fvalue) {
      // 变更时段节点
      let bgsdNode = _.find(businessObjectDesList, { "fieldid": "checktypearray" });
      //console.log(bgsdNode);
      // 变更日期节点
      let bgrqNode = _.find(businessObjectDesList, { "fieldid": "checktimearray" });
      //console.log(bgrqNode);
      bgsdNode["fvalue"] = _.toString(_.map(node.fvalue, "value1")); // 变更时段
      bgrqNode["fvalue"] = _.toString(_.map(node.fvalue, "value2")); // 考勤变更时间
    }

    //console.log(_.find(this.businessObjectDesList, { "fieldid": "checktypearray" })["fvalue"]);
    //console.log(_.find(this.businessObjectDesList, { "fieldid": "checktimearray" })["fvalue"]);
  }
  // 变更明细控件 END

  /**
   * [createBGMXNode 构建变更明细节点]
   * @param {[businessObjectDesList]} item [businessObjectDesList]
   */
  createBGMXNode(businessObjectDesList) {
    var node = {
      "fieldid": "ext-bgmx",
      "type": "EXT-BT01",
      "fname": "变更明细",
      "fieldidCol": ["checktypearray", "checktimearray"],  // 变更时段feildid,变更日期feildid
      "isShow": true, // 是否显示控件
      "fvalue": [{
        "isShow": false, // 是否展开显示
        "title1": "变更时段",
        "value1": "1", // 1:上午, 2:下午, 3:全天
        "title2": "考勤变更日期",
        "value2": this.common.getLastDay()
      }]
    }

    console.log(businessObjectDesList);

    // 修改'变更时段'和'考勤变更时间'节点的fvalue
    this.bgmxChange(node, businessObjectDesList);
    return node;
  }

  initBGMXNode(businessObjectDesList) {
    let node = {
      "fieldid": "ext-bgmx",
      "type": "EXT-BT01",
      "fname": "变更明细",
      "fieldidCol": ["checktypearray", "checktimearray"],  // 变更时段feildid,变更日期feildid
      "isShow": true, // 是否显示控件
      "fvalue": []
    };

    let checktimearrayField = _.find(businessObjectDesList, {"fieldid": "checktimearray"});
    let checktypearrayField = _.find(businessObjectDesList, {"fieldid": "checktypearray"});
    let checktimearrayFieldValues = _.split(checktimearrayField["fvalue"], ",");
    let checktypearrayFieldValues = _.split(checktypearrayField["fvalue"], ",");
    _.forEach(checktimearrayFieldValues, (value, i) => {
      let valueObj = {
        "isShow": false, // 是否展开显示
        "title1": "变更时段",
        "value1": checktypearrayFieldValues[i], // 1:上午, 2:下午, 3:全天
        "title2": "考勤变更日期",
        "value2": value
      };
      node["fvalue"].push(valueObj);
    });
    return node;
  }

  // 变更明细控件 START
  /**
   * [addBGMX 变更明细控件，增加明细]
   * @param {[type]} item [description]
   */
  addBGMX(item, businessObjectDesList) {
    var node = {
      "isShow": true,
      "title1": "变更时段",
      "value1": "1",
      "title2": "考勤变更日期",
      "value2": this.common.getLastDay()
    };
    item.fvalue.push(node);
    // 修改'变更时段'和'考勤变更时间'节点的fvalue
    this.bgmxChange(item, businessObjectDesList);
  }
  /**
   * [deleteBGMXNode 删除变更明细某一项]
   * @param {[type]} item  [description]
   * @param {[type]} index [description]
   */
  deleteBGMXNode(item, index, businessObjectDesList) {
    console.log("##draft.service.deleteBGMXNode 删除节点");
    // 如果只有一条变更明细，那么不能删除
    if (item.fvalue.length > 1) {
      _.pullAt(item.fvalue, index);
      // 修改'变更时段'和'考勤变更时间'节点的fvalue
      this.bgmxChange(item, businessObjectDesList);
    }
  }


  // 年休假信息控件
  createNXJXXNode() {
    var node = {
      "fieldid": "ext-nxjxx",
      "type": "EXT-BT02",
      "fname": "显示年休假信息",
      "fvalue": [{ "title": "今年可休年休假天数", "fvau": "", "numb": "maydays", "color": "" },
        { "title": "今年调整后可休年假", "fvau": "", "numb": "tzhkxDays", "color": "" },
        { "title": "今年已休年休假天数", "fvau": "", "numb": "alreadydays", "color": "" },
        { "title": "今年剩余可休年假天数", "fvau": "", "numb": "restdays", "color": "redColor" },
        { "title": "明年可休年休假天数", "fvau": "", "numb": "mmaydays", "color": "" },
        { "title": "明年调整后可休年假", "fvau": "", "numb": "mtzhkxDays", "color": "" },
        { "title": "明年已休年休假天数", "fvau": "", "numb": "malreadydays", "color": "" },
        { "title": "明年剩余可休年假天数", "fvau": "", "numb": "mrestdays", "color": "redColor" }]
    };

    this.getAnnualLeave().subscribe(data => {
      if (data && data.refenDtos) {
        _.forEach(node.fvalue, function(fvalue) {
          if (fvalue["numb"] != "restdays" && fvalue["numb"] != "mrestdays") {
            fvalue["fvau"] = _.find(data.refenDtos, {"skey": fvalue.numb})["svalue"];
          }
        });

        let tzhkxDaysValue = _.find(data.refenDtos, {"skey": "tzhkxDays"})["svalue"];
        let alreadydaysValue = _.find(data.refenDtos, {"skey": "alreadydays"})["svalue"];
        let restdaysNode = _.find(node.fvalue, {"numb": "restdays"});
        let mtzhkxDaysValue = _.find(data.refenDtos, {"skey": "mtzhkxDays"})["svalue"];
        let malreadydaysValue = _.find(data.refenDtos, {"skey": "malreadydays"})["svalue"];
        let mrestdaysNode = _.find(node.fvalue, {"numb": "mrestdays"});

        restdaysNode["fvau"] = (parseFloat(tzhkxDaysValue) - parseFloat(alreadydaysValue)).toFixed(2);
        mrestdaysNode["fvau"] = (parseFloat(mtzhkxDaysValue) - parseFloat(malreadydaysValue)).toFixed(2);


      }
    });

    return node;
  }

  /**
   * [checkStartEndTime 开始时间不小于结束时间返回false,否则返回true]
   * @param {[type]} item [description]
   */
  checkStartEndTime(businessObjectDesList) {
    console.log("##draft.service.checkStartEndTime 比较开始结束时间");
    var that = this;
    var retVal = true;
    let startdateFvalue = _.find(businessObjectDesList, { "fieldid": "startdate" })["fvalue"]; // 起始日期
    let startpointFvalue = _.find(businessObjectDesList, { "fieldid": "startpoint" })["fvalue"]; // 开始时间
    let enddateFvalue = _.find(businessObjectDesList, { "fieldid": "enddate" })["fvalue"]; // 结束日期
    let endpointFvalue = _.find(businessObjectDesList, { "fieldid": "endpoint" })["fvalue"]; // 结束时间

    // 构建时间，如：2017-03-06 15:00:00
    let startTime = startdateFvalue + " " + startpointFvalue + ":00";
    let endTime = enddateFvalue + " " + endpointFvalue + ":00";

    if (startTime >= endTime) {
      retVal = false; // 开始时间大于或等于结束时间
    } else {
      retVal = true;
    }

    return retVal;
  }

  /**
   * [calculateQJTX 计算请假天数,并给'请假天数'节点赋值]
   * @param {[type]} item [description]
   */
  calculateQJTX(item, businessObjectDesList, alertCtrl) {
    console.log("##draft.service.calculateQJTX 计算请假天数");

    let params = {};
    let startdateFvalue = _.find(businessObjectDesList, { "fieldid": "startdate" })["fvalue"]; // 起始日期
    let startpointFvalue = _.find(businessObjectDesList, { "fieldid": "startpoint" })["fvalue"]; // 开始时间
    let enddateFvalue = _.find(businessObjectDesList, { "fieldid": "enddate" })["fvalue"]; // 结束日期
    let endpointFvalue = _.find(businessObjectDesList, { "fieldid": "endpoint" })["fvalue"]; // 结束时间
    let resttypeFvalue = _.find(businessObjectDesList, { "fieldid": "resttype" })["fvalue"]; // 休假类型
    let restdaysNode = _.find(businessObjectDesList, { "fieldid": "restdays" }); // 请假天数

    if (!startdateFvalue || !startpointFvalue || !enddateFvalue || !endpointFvalue) {
      return false;
    }

    restdaysNode["fvalue"] = "计算休假天数中...";

    // 构建时间，如：2017-03-06 15:00:00
    params["dateStart"] = startdateFvalue + " " + startpointFvalue + ":00";
    params["dateEnd"] = enddateFvalue + " " + endpointFvalue + ":00";

    params["resttype"] = resttypeFvalue;
    // console.log(params["dateStart"]);
    // console.log(params["dateEnd"]);
    // console.log(params["resttype"]);

    this.calculateDays(params).subscribe(data => {
      try {
        let num = _.toNumber(data);
        if (new Date(params["dateStart"].replace(/-/g, "/")) > new Date(params["dateEnd"].replace(/-/g, "/"))) {
          restdaysNode["fvalue"] = 0 - num;
        } else {
          restdaysNode["fvalue"] = num;

          //判断年休假弹出提示
          let resttype_node = _.find(businessObjectDesList, {"fieldid": "resttype"});
          let yearRest = _.find(resttype_node["fieldvalDtos"], {"fdval": "年休假"});
          if (resttype_node["fvalue"] === yearRest["fvau"]) {
            this.storage.get("userInfo").then( userInfo => {
              let ckParams = {
                "empid": userInfo.empid,
                "resttype": resttype_node["fvalue"],
                "startdate": startdateFvalue,
                "startpoint": startpointFvalue + ":00",
                "enddate": enddateFvalue,
                "endpoint": endpointFvalue + ":00",
                "restdays": restdaysNode["fvalue"]
              };
              this.ckHrAnnualDay(ckParams).subscribe( ckResult => {
                if (ckResult != "success") {
                  this.common.alertMessage(ckResult);
                  _.find(businessObjectDesList, { "fieldid": "startpoint" })["fvalue"] = "";
                  _.find(businessObjectDesList, { "fieldid": "endpoint" })["fvalue"] = "";
                  restdaysNode["fvalue"] = "";
                }
              });
            });
          }
        }

      } catch (error) {
        restdaysNode["fvalue"] = "";
      }
    });
  }



  /**
   * [resttypeChange 如果选择的不是休年假，则隐藏年假信息节点]
   * @param {[type]} item                  [description]
   * @param {[type]} businessObjectDesList [description]
   */
  resttypeChange(item, businessObjectDesList) {
    let node = _.find(businessObjectDesList, { "fieldid": "ext-nxjxx" });
    // 如果选的不是休假，隐藏'年休假节点'
    if (item["fvalue"] == "91699") {
      node["isShow"] = true;
    } else {
      node["isShow"] = false;
    }
  }
  /**
   * [isFundManager 判断当前用户是否基金经理]
   */
  isFundManager(){
    let  that = this;
    let promise = new Promise(function (resolve, reject) {
      that.storage.get('userInfo').then((userInfo) => {
        if (userInfo) {
          that.storage.get('contact-org-list').then(data => {
            let isFund = false;
            _.each(data,function(org,i){
              if (org.name.indexOf("contact-list-org-third") > -1) {
                var user = _.find(org.list, { "full_orgname": "群组/基金经理","loginid": userInfo.loginid});
                if(user) {
                  isFund = isFund || true;
                }
              }
            });
            resolve(isFund);
          });
        }
      });
    });
    return promise;
  }
  /**
   * [setFundMgrPro 设置出差申请流程基金经理，是否申请投资系统自由交易授权]
   * @param {[type]} listData [businessObjectDesList]
   * @param {[type]} isFundMgr [bool]
   */
  setFundMgrPro(listData,isFundMgr){
    //console.log("isFundMgr:" + isFundMgr);
    let isApplyTZXTQX = _.find(listData, { "fieldid": "isApplyTZXTQX" });
    console.log(isApplyTZXTQX);
    if(isApplyTZXTQX){
      isApplyTZXTQX["isShow"] = isFundMgr;
      if(isFundMgr){
        isApplyTZXTQX["allowNull"] = false;
      }
    }
    console.log(isApplyTZXTQX);
    return listData;
  }
  /**
   * [setIsFundMgr 根据选择是否申请投资系统自由交易授权，设置isfundmgr=YES]
   * @param {[type]} businessObjectDesList [businessObjectDesList]
   */
  setIsFundMgr(businessObjectDesList){
    console.log(businessObjectDesList);
    let isApplyTZXTQX = _.find(businessObjectDesList, { "fieldid": "isApplyTZXTQX" })["fvalue"]; // 是否申请投资系统自由交易授权
    if(isApplyTZXTQX == "YES"){
      businessObjectDesList.push({"fieldid": "isFundMgr","fvalue" : "YES"});
    }
  }

  getAddress() {
    let postBody = {
      "module": "OAServer",
      "method": "getAddress",
      "params": {

      }
    }

    return this.httpClient.post(postBody, {
      isShowLoading: true
    });
  }

  getCompanyCode(page, keyWord) {
    let postBody = {
      "module": "OAServer",
      "method": "getCompanyCode",
      "params": {
        "keyWord": keyWord,
        "pageIndex": page,
        "pageSize": this.config.pageSize
      }
    };

    return this.httpClient.post(postBody, {
      isShowLoading: true
    });
  }

  getIndustryInfo(page, keyWord) {
    let postBody = {
      "module": "OAServer",
      "method": "getIndustryInfo",
      "params": {
        "keyWord": keyWord,
        "pageIndex": page,
        "pageSize": this.config.pageSize
      }
    }

    return this.httpClient.post(postBody, {
      isShowLoading: true
    });
  }

// <<<<<<< HEAD
  getLeaveType() {
    let postBody: any = {
      "module": "OAServer",
      "method": "getLeaveType",
      "params": {}
    };
    return this.httpClient.post(postBody, {
      isShowLoading: true
    });
  }
  calcLeaveDays(item, dataList, leaveType): void {
    let params: any = {},
      type: string = item.qjtype,
      startDate: string = item.ksrq,
      startTime = item.kssj,
      endDate: string = item.jsrq,
      endTime: string = item.jssj;
    item.qjts = "计算休假天数中...";
    params["resttype"] = type;
    params["dateStart"] = startDate + " " + startTime + ":00";
    params["dateEnd"] = endDate + " " + endTime + ":00";
    this.calculateDays(params).subscribe((data: any) => {
      try {
		console.log(data);
        let num = _.toNumber(data);
        if (new Date(params["dateStart"].replace(/-/, "/")) > new Date(params["dateEnd"].replace(/-/, "/"))) {
          item.qjts = 0 - num;
        } else {
          item.qjts = num;
        }
        let restTypeNode = _.find(leaveType, type => {
          return type["entry"]["bostitle"] === "年休假";
        });
        if (item.qjtype === restTypeNode["entry"]["bosid"]) {
          console.log("<<<<<<<出境申请休假明细-年休假>>>>>>");
          let nxjList = _.filter(dataList, data => {
            return data["qjtype"] === item.qjtype && data["kssj"] != "" && data["jssj"] != "";
          });
          let startDate = _.min(_.map(nxjList, "ksrq"));
          let startTime = _.min(_.map(nxjList, "kssj"));
          let endDate = _.max(_.map(nxjList, "jsrq"));
          let endTime = _.max(_.map(nxjList, "jssj"));
          this.storage.get("userInfo").then( userInfo => {
            let ckParams = {
              "empid": userInfo.empid,
              "resttype": item.qjtype,
              "startdate": startDate,
              "startpoint": startTime + ":00",
              "enddate": endDate,
              "endpoint": endTime + ":00",
              "restdays": item.qjts
            };
            console.log("ckParams>>>>>>>>>>", ckParams);
            this.ckHrAnnualDay(ckParams).subscribe( ckResult => {
              console.log("ckResult>>>>>>>>>>>>", ckResult);
              if (ckResult != "success") {
                this.common.alertMessage(ckResult);
                item.kssj = "";
                item.jssj = "";
                item.qjts = "";
              }
            });
          });
        }
      } catch (error) {
        item.qjts = "请输入时间段";
      }
    });
  }
  insertCJMXDetail(bosid, leaveEntry) {
    let that = this,
      postBody = {
        module: "OAServer",
        method: "insertCJMXDetail",
        params: {
          bosid: bosid,
          fieldValueList: []
        }
      },
      fieldValueList = [];
    leaveEntry.forEach((entry: any) => {
      entry["glbosid"] = bosid;
      let keys: any[] = _.keys(entry),
        entrys: any[] = [];
      keys.forEach((key: any) => {
        let temp: any = {
          key: {
            attributes: that.common.attributes,
            $value: key
          },
          value: {
            attributes: that.common.attributes,
            $value: entry[key]
          }
        };
        entrys.push(temp);
      });
      fieldValueList.push({
        fieldValueMap: {
          entry: entrys
        }
      });
    });
    console.log(leaveEntry, postBody);
    postBody.params.fieldValueList = fieldValueList;
    return this.httpClient.post(postBody, {
      isShowLoading: true
    });
  }

// =======
  getChuChaiDetailData(bosid) {
    let postBody = {
      "module": "OAServer",
      "method": "getChuChaiDetailData",
      "params": {
        "bosid": bosid
      }
    };
    return this.httpClient.post(postBody, {
      isShowLoading: false
    })
  }

  getChuJingDetailData(bosid) {
    let postBody = {
      "module": "OAServer",
      "method": "getChuJingDetailData",
      "params": {
        "bosid": bosid
      }
    };
    return this.httpClient.post(postBody, {
      isShowLoading: false
    })
  }

  /**
   * [ipoDetailData]
  */
  ipoDetailData(value, marketVal, businessObjectDesList) {

    /*let postBody = {
      "module": "KSB",
      "method": "FOS_A02_0220",
      "format": "json",
      "params": {
       "vc_inter_code": value,
       "c_market_no": ""
      }
    };

    //设置市场后缀和市场码
    if (marketVal == 'H') {
      postBody.params.vc_inter_code += 'SS';
      postBody.params.c_market_no = "1";
    }else if (marketVal == 'S'){
      postBody.params.vc_inter_code += 'SZ';
      postBody.params.c_market_no = "2";
    }*/

    if (this.type === 'xgipoxj') {
      let that = this;

      this.getCodeDataByKSB(value, marketVal).subscribe(data => {
        let ipoxjDictionary = {
          "industry": "sectors",
          "certinm": "vc_stock_name",
          "issuestotstock": "issueshares_check",
          "ipototstock": "est_postissueshares_m_wd",
          "webipototstock": "ipo_olpurchaseamount_10k_wd",
          "preipoassets": "netassetpreipo_fc",
          "diforecast": "tbyjyc",
          "preipoincome": "assetpreipo_fc",
          "totnegcap": "FLOATQTYPOSTIPO_WD",
          "minbuy": "lower_applyamount_check",
          "maxbuy": "upper_applyamount_check",
          "minnum": "offlsubminproqty_check",
          "InquiryStartDay": "en_begin_date_check",
          "wxsgDay": "ipo_applystartdate_check",
          "HKdate": "OFFLPAYDATE_CHECK",
          "miniValue": "S_IPO_MV_THRESHOLD_WD"
        }
        if (data) {

          _.forEach(ipoxjDictionary, function(val, key) {
            _.find(businessObjectDesList, {fieldid: key})["fvalue"] = data[0][val];

            if (key == 'InquiryStartDay' || key == 'wxsgDay') {
              let queryDay = data[0].en_begin_date_check.replace(/^(\d{4})(\d{2})(\d{2})$/, "$1-$2-$3");
              let _wxsgDay = data[0].ipo_applystartdate_check.replace(/^(\d{4})(\d{2})(\d{2})$/, "$1-$2-$3");
              _.find(businessObjectDesList, {fieldid: 'InquiryStartDay'})["fvalue"] = queryDay;
              _.find(businessObjectDesList, {fieldid: 'wxsgDay'})["fvalue"] = _wxsgDay;
            }

          });
        }else {
          _.forEach(ipoxjDictionary, function(val, key) {
            _.find(businessObjectDesList, {fieldid: key})["fvalue"] = '';
          });
        }
      });
    } else if(this.type === 'xgiposg'){

      let defObj = {};
      //先查看通用服务是否有数据，没有则调KSB
      this.getIPODefVal(value, marketVal).subscribe(data => {

        if (data) {
          console.log('-------commom-------', data)
          let _data = data[0]['fieldValueMap']['entry'];
          _data.forEach(function(item){
            let _key = item['key']['$value'];
            let _val = '';
            if (item['value']) {
              _val = item['value']['$value'];
            }
            defObj[_key] = _val;
          })

          let replaceField = {
            "diforecast": "DilForecast",
            "predictrate": "RateForecast",
          }

          _.forEach(replaceField, function(val, key ){
            defObj[val] = defObj[key]
          })
          _.forEach(defObj, function(val, key) {
            try {
              _.find(businessObjectDesList, {fieldid: key})["fvalue"] = val;
            } catch(err){

            }
          });
        } else {

          this.getCodeDataByKSB(value, marketVal).subscribe(data => {
            let iposgDictionary = {
              "CertiNm": "vc_stock_name",
              "industry": "sectors",
              "IPOTotStock": "est_postissueshares_m_wd",
              "WebIPOTotStock": "ipo_olpurchaseamount_10k_wd",
              "PreIPOAssets": "netassetpreipo_fc",
              "DilForecast": "tbyjyc",
              "PreIPOIncome": "assetpreipo_fc",
              "IssuesTotStock": "issueshares_check",
              "TotNegCap": "FLOATQTYPOSTIPO_WD"
            }

            if (data) {
              _.forEach(iposgDictionary, function(val, key) {
                _.find(businessObjectDesList, {fieldid: key})["fvalue"] = data[0][val];
              });
            }else {
              _.forEach(iposgDictionary, function(val, key) {
                _.find(businessObjectDesList, {fieldid: key})["fvalue"] = '';
              });
            }
          })
          /*let clearField = ["CertiNm", "DilForecast", "IPOTotStock", "IssuePrice", "IssuesTotStock", "LeadUnderWriter", "PreIPOAssets", "PreIPOIncome", "RateForecast", "TotNegCap", "WebIPOTotStock", "industry"];
          _.forEach(clearField, function(item) {
            _.find(businessObjectDesList, {fieldid: item})["fvalue"] = '';
          })*/
        }
      });
    }

  }

  /**
   * [getUnderwriter 获取承销商]
  */
  getUnderwriter(item, businessObjectDesList) {
    let postBody = {
      "module": "KSB",
      "method": "INF_002_0060",
      "format": "json",
      "params": {
        "S_INFO_WINDCODE": item["fvalue"]
      }
    };

    return this.httpClient.post(postBody, {
      isShowLoading: false
    }).subscribe( data => {
      if ( this.type === 'xgipoxj' ) {
        if (data) {
          _.find(businessObjectDesList, {fieldid: "leadunderwriter"})["fvalue"] = data[0]["S_LU_NAME"];
        }else {
          _.find(businessObjectDesList, {fieldid: "leadunderwriter"})["fvalue"] = '';
        }
      } else if ( this.type === 'xgiposg') {
        if (data) {
          _.find(businessObjectDesList, {fieldid: "LeadUnderWriter"})["fvalue"] = data[0]["S_LU_NAME"];
        }else {
          _.find(businessObjectDesList, {fieldid: "LeadUnderWriter"})["fvalue"] = '';
        }
      }
    })
  }

  /**
   * [getIPODefVal 网上申购调取通用接口]
  */
  getIPODefVal(value, marketVal) {
    let postBody = {
      "module": "CommonTools",
      "method": "getNormalTableData",
      "params": {
        "loginId": "system",
        "tableName": "T_TZ_Inquiry",
        "returnId": "CertiNm,industry,IssuesTotStock,PreIPOAssets,PreIPOIncome,IPOTotStock,diforecast,WebIPOTotStock,TotNegCap,LeadUnderWriter,predictrate,IssuePrice",
        "condition": " and certiid = '" + value + "' and market = '" + marketVal + "'",
        "orderby": "bosid desc"
      }
    }
    return this.httpClient.post(postBody, {
      isShowLoading: false
    })
  }

  /**
   * [getIPODefVal 新股询价、申购调取KSB接口]
  */
  getCodeDataByKSB(value, marketVal) {
    let postBody = {
      "module": "KSB",
      "method": "FOS_A02_0220",
      "format": "json",
      "params": {
       "vc_inter_code": value,
       "c_market_no": ""
      }
    };

    //设置市场后缀和市场码
    if (marketVal == 'H') {
      postBody.params.vc_inter_code += 'SS';
      postBody.params.c_market_no = "1";
    }else if (marketVal == 'S'){
      postBody.params.vc_inter_code += 'SZ';
      postBody.params.c_market_no = "2";
    }

    return this.httpClient.post(postBody, {
      isShowLoading: true,
    })
  }
}
// >>>>>>> d0dd4def41a44c87c4c64a6af4c2d5e463dcd939
